package com.yicong.ants.utils

import android.content.Context
import android.os.Build
import android.os.StrictMode
import cn.jiguang.api.utils.JCollectionAuth
import cn.jiguang.jmlinksdk.api.JMLinkAPI
import com.alibaba.security.realidentity.RPVerify
import com.aliyun.TigerTally.TigerTallyAPI
import com.blankj.utilcode.util.SPUtils
import com.bun.miitmdid.core.MdidSdkHelper
import com.bun.miitmdid.interfaces.IdSupplier
import com.cchao.simplelib.LibCore
import com.cchao.simplelib.core.Logs
import com.cchao.simplelib.core.UiHelper
import com.cchao.simplelib.http.AliDns
import com.cchao.simplelib.util.StringHelper
import com.cchao.simplelib.util.UrlUtil
import com.cchao.simplelib.util.UuidUtil
import com.dueeeke.videoplayer.player.VideoViewConfig
import com.dueeeke.videoplayer.player.VideoViewManager
import com.geetest.onelogin.OneLoginHelper
import com.tencent.smtt.export.external.TbsCoreSettings
import com.tencent.smtt.sdk.QbSdk
import com.tencent.smtt.sdk.QbSdk.PreInitCallback
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.utils.Md5Utils
import com.umeng.analytics.MobclickAgent
import com.umeng.cconfig.RemoteConfigSettings
import com.umeng.cconfig.UMRemoteConfig
import com.umeng.commonsdk.UMConfigure
import com.umeng.socialize.PlatformConfig
import com.volcengine.mobsecBiz.metasec.ml.MSConfig
import com.volcengine.mobsecBiz.metasec.ml.MSManagerUtils
import com.x.livesdk.LiveSdk
import com.yicong.ants.App
import com.yicong.ants.BuildConfig
import com.yicong.ants.Constants
import com.yicong.ants.R
import com.yicong.ants.bean.account.UserBean
import com.yicong.ants.manager.AppHelper
import com.yicong.ants.manager.BusinessHelper
import com.yicong.ants.manager.PayManager
import com.yicong.ants.manager.UserManager
import com.yicong.ants.manager.config.ZzConfigs
import com.zhy.http.okhttp.OkHttpUtils
import com.zx.sdk.ZxSDK
import com.zx.sdk.listener.ZxHostAppListener
import com.zx.sdk.util.LogHelper
import com.zx.sdk.util.RunnableHelper
import com.zx.sdk.util.RunnableHelper.tryRun
import com.zx.sdk.util.ZxEventHelper
import com.zx.sdk.util.ZxEventHelper.ZxEventHandler
import okhttp3.OkHttpClient
import java.util.concurrent.TimeUnit


object InitUtil {
    private var isOaidOk = false
    private var init = false
    fun isInit(): Boolean {
        return init
    }

    fun init(context: Context) {
        init = true
        ZzConfigs.init()
        initHs(context)
        initLog()
        initHttp()
        initAd(context)
        initUMeng(context)
        initJpush(context)
        initTigerTally()
        initX5(context)
        // 视频播放器初始化
        tryRun { initPlayer() }
        // 一键登录
        if (UserManager.notLogin()) {
            tryRun {
                OneLoginHelper.with() //开启 SDK 日志打印功能
                    .setLogEnable(true)
                    .init(LibCore.getContext(), Constants.GeeTestID)
                    .register(Constants.GeeTestID, 5000)
            }
        }
        // 初始化实人认证SDK。
        tryRun { RPVerify.init(LibCore.getContext()) }
        // 相机初始化
        tryRun { initCamera() }
        // 初始化微信
        tryRun { PayManager.registerWxApi() }
        // oaid
        tryRun {
            MdidSdkHelper.InitSdk(
                LibCore.getContext(),
                true
            ) { b: Boolean, idSupplier: IdSupplier? ->
                if (idSupplier == null || !idSupplier.isSupported
                    || StringHelper.isEmpty(idSupplier.oaid)
                    || idSupplier.oaid.startsWith("000")
                    || idSupplier.oaid.length < 8
                ) {
                    setZID(context)
                    return@InitSdk
                }
                Logs.d("oaid " + b + " " + idSupplier.oaid)
                isOaidOk = true
                UuidUtil.setAndWriteUuid(idSupplier.oaid)
            }
        }
        // 如果2秒钟以后Oaid还没有设置成功，则使用zid
        RunnableHelper.postDelay(2000) {
            if (!isOaidOk) {
                setZID(context)
            }
        }
        InitImUtils.init(context)
    }

    private fun initHs(context: Context) {
        val builder = MSConfig.Builder(
            App.hsAppID,
            "z3V1zm8hGKzhKNWptVcW9McPKnkKI8tMiJbYhBvN2CGWb7kmR+s4kWBAoyYV51DPfmmS7e5Papqfd/EErgyykbI6Jy8uZpb+jUEH0T/gNif9Lf48wkNogfUjFd5vbAW7SExY9kay7i7t6qmvpoUH38ef2lWzW92yoLpjbkxTFZlbvYU0DjBgM4dazGbpvIzGPFFLhnpK/5aZmG86EW3QH+bNXJCUT6+ZkCrNwJux3vNSM5W4K3v6b8N6RYO98GN8NEEGQ9l5/nNe/F7UYosQqppXNmZZeHg3xm9NGLU54FAGG/nH",
            MSConfig.COLLECT_MODE_DEFAULT
        )
        //正常采集模式：MSConfig.COLLECT_MODE_DEFAULT
        //基础采集模式：MSConfig.COLLECT_MODE_ML_MINIMIZE
        //正常采集模式：MSConfig.COLLECT_MODE_DEFAULT
        //基础采集模式：MSConfig.COLLECT_MODE_ML_MINIMIZE
        val config = builder
            .setChannel("default")
            .addDataObserver { token: String? -> }
            .build()
        MSManagerUtils.init(context, config)
    }

    private fun setZID(context: Context) {
        val zid = UMConfigure.getUmengZID(context)
        if (StringHelper.isEmpty(zid)) return
        UuidUtil.setAndWriteUuid(Md5Utils.getMD5(zid + Build.FINGERPRINT))
    }

    private fun initX5(context: Context) {
        val map = HashMap<String, Any>()
        map[TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER] = true
        map[TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE] = true
        QbSdk.initTbsSettings(map)
        QbSdk.initX5Environment(context, object : PreInitCallback {
            override fun onCoreInitFinished() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    val processName = AppHelper.getCurrentProcessName(context)
                    if (context.packageName != processName) { //判断是否是默认进程名称
                        WebView.setDataDirectorySuffix(processName)
                        android.webkit.WebView.setDataDirectorySuffix(processName)
                    }
                }
            }

            /**
             * 预初始化结束
             * 由于X5内核体积较大，需要依赖网络动态下发，所以当内核不存在的时候，默认会回调false，此时将会使用系统内核代替
             * @param isX5 是否使用X5内核
             */
            override fun onViewInitFinished(isX5: Boolean) {}
        })
        QbSdk.setDownloadWithoutWifi(true)
    }

    @JvmStatic
    fun initTigerTally() {
        TigerTallyAPI.setAccount(UserManager.getUserId())
        TigerTallyAPI.init(
            LibCore.getContext(),
            "v-ypYkexw30kiDvHs5xiGObpRbCMyFEUnrCvWfAy8CGDrewzvz7cQ1iDb8eIpX1nASPguDXIrmcmVJSCR1_dQ5V0G2dYQ9a7kiH9Glq_QGRYYo7qhxML_NBgTg33P69p30SRjbsmgy9tI-BmD-ET_rfLXIEIJSyI9PWuSjD-xRM=",
            TigerTallyAPI.CollectType.DEFAULT
        )
    }

    @JvmStatic
    fun initAd(context: Context) {
        val isLogShown =
            SPUtils.getInstance("zx_sdk_share_data").getBoolean(LogHelper.KEY_ADV_LOGS, false)
        ZxSDK.init(
            context,
            UiHelper.getString(R.string.ad_appid),
            BuildConfig.VERSION_CODE,
            UiHelper.getString(R.string.app_name),
            "https://ssp-api.yctourism.com",
            AppHelper.isTestEnv() || BuildConfig.Ant_Debug || isLogShown,
            context.getString(R.string.key_wx_app),
            object : ZxHostAppListener {
                override fun getUserId(): String {
                    return UserManager.getUserId()
                }

                override fun getToken(): String {
                    return try {
                        MSManagerUtils.get(App.hsAppID).token
                    } catch (e: Exception) {
                        "";
                    }
                }

                override fun getUserToken(): String {
                    if (UserManager.isLogin()) {
                        return UserManager.getUserBean().jwt_token
                    }
                    return ""
                }

                override fun getZxEventHandler(): ZxEventHandler {
                    return ZxEventHandler { leagueName: String, position: String, _: String?, mobPid: String, event: String ->
                        val map = HashMap<String, Any>()
                        val tmpMobPid = mobPid.replace("@@", "_")
                        map[tmpMobPid] = event
                        val key = leagueName + "_" + position
                        MobclickAgent.onEventObject(LibCore.getContext(), key, map)
                        LogHelper.d("onEventObject", key, map.toString())
                        // 曝光事件单独记录一份
                        if (event == ZxEventHelper.EXPOSE) {
                            val map2: MutableMap<String, Any> = HashMap()
                            map2[leagueName] = tmpMobPid
                            MobclickAgent.onEventObject(LibCore.getContext(), "ad_expose", map2)
                        }
                    }
                }

                override fun getMobile(): String {
                    return UserManager.getMobile()
                }

                override fun getDeviceId(): String {
                    return ""
                }
            })
    }

    fun initPlayer() {
        //播放器配置，注意：此为全局配置，按需开启
        VideoViewManager.setConfig(
            VideoViewConfig.newBuilder()
                .setLogEnabled(AppHelper.isDebug()) //调试的时候请打开日志，方便排错
                //            .setPlayerFactory(IjkPlayerFactory.create())
                //                .setPlayerFactory(ExoMediaPlayerFactory.create())
                //                .setRenderViewFactory(SurfaceRenderViewFactory.create())
                //                .setEnableOrientation(true)
                //                .setEnableAudioFocus(false)
                //                .setScreenScaleType(VideoView.SCREEN_SCALE_MATCH_PARENT)
                //                .setAdaptCutout(false)
                .setPlayOnMobileNetwork(true) //                .setProgressManager(new ProgressManagerImpl())
                .build()
        )
    }

    private fun initLog() {
        L.setIsDebug(LibCore.isDebug())
    }

    private fun initUMeng(context: Context) {
        AppHelper.tryRun {

            // 在线参数
            UMRemoteConfig.getInstance()
                .setConfigSettings(
                    RemoteConfigSettings.Builder().setAutoUpdateModeEnabled(true)
                        .build()
                )
            UMConfigure.preInit(context, "5f648f0fa4ae0a7f7d08a609", "default")
            UMConfigure.init(
                context,
                "5f648f0fa4ae0a7f7d08a609",
                "default",
                UMConfigure.DEVICE_TYPE_PHONE,
                "a5f0ded62a72774175cb4928ec32392a"
            )
            UMConfigure.setLogEnabled(AppHelper.isDebug())
            PlatformConfig.setWeixin("wxb7aa912b2ee0cf03", "01a9e3e4898c0d767444221561c7f4fe")
            PlatformConfig.setWXFileProvider("com.yicong.ants.fileprovider")
        }
    }

    //极光推送
    private fun initJpush(context: Context) {
        if (BuildConfig.STORE) {
            return
        }
        JCollectionAuth.setAuth(context, true)
        JMLinkAPI.getInstance().setDebugMode(AppHelper.isDebug())
        JMLinkAPI.getInstance().init(context)
    }

    fun initCamera() {
        // android 7.0系统解决拍照的问题
        val builder = StrictMode.VmPolicy.Builder()
        StrictMode.setVmPolicy(builder.build())
        builder.detectFileUriExposure()
    }

    private fun initHttp() {
        AppHelper.tryRun {
            AliDns.init()
            val okHttpClient =
                OkHttpClient.Builder() // 添加 OkHttp 拦截器 .addInterceptor(new LoggerInterceptor("TAG"))
                    .connectTimeout(Constants.CONN_TIME_OUT.toLong(), TimeUnit.MILLISECONDS)
                    .readTimeout(Constants.READ_TIME_OUT.toLong(), TimeUnit.MILLISECONDS)
                    .writeTimeout(Constants.WRITE_TIME_OUT.toLong(), TimeUnit.MICROSECONDS)
                    .retryOnConnectionFailure(true)
//                    .dns(AliDns.get()) //其他配置
                    .build()
            OkHttpUtils.initClient(okHttpClient)
        }
    }

    fun initLiveSDK(context: Context) {
        var userBean = UserManager.getUserBean()
        if (userBean == null) {
            userBean = UserBean()
        }
        LiveSdk.init(
            context,
            ZzConfigs.getClientConf().web_url["live_api"]?.url ?: "",
            AppHelper.isTestEnv()
        )
        LiveSdk.appcode = "ant"
        LiveSdk.app_id = LibCore.getInfo().appId.toString()
        LiveSdk.appVersion = BuildConfig.VERSION_CODE.toString()
        LiveSdk.userId = userBean.id
        LiveSdk.nickname = userBean.nickname
        LiveSdk.avatar = userBean.avatar
        LiveSdk.token = userBean.jwt_token
        LiveSdk.source = "ant"
        LiveSdk.uuid = UuidUtil.getUniqueID(LibCore.getContext())
        LiveSdk.onStartWebActivityListener = { ctx, title, url ->
            ZzConfigs.toWebActivity(ctx, title, url)
        }
        LiveSdk.onShareListener = { title, subTitle, cover, url , callBack ->
            BusinessHelper.shareWx(
                App.mLifecycleCallListener.mTopActivity,
                title,
                subTitle,
                cover,
                UrlUtil.appendParameterCompat(url, "other", "ant_ant"),
                callBack
            )
        }
//        val config: LiveSdkConfig = if (AppHelper.isTestEnv()) {
//            LiveSdkConfig(
//                "5h5fuq",
//                "20915f378ddfe3ec0db2dee0b71fc359",
//                "http://106.14.91.96:8080",
//                "1b6d5e5d-2908-439f-971d-2a06ba13c049",
//                userBean.id,
//                userBean.nickname,
//                userBean.avatar,
//                "http://live.api.ant.yc1024dev.cn",
//                userBean.jwt_token,
//                "ant",
//                "ant", LibCore.getInfo().appId.toString(),
//                UuidUtil.getUniqueID(LibCore.getContext()),
//                Build.MODEL, BuildConfig.VERSION_CODE.toString()
//            )
//        } else {
//            LiveSdkConfig(
//                "9jmc99",
//                "5040d05a60f69fad45eaed5332938f8b",
//                "http://47.103.134.114:8080",
//                "7d5461a6-6f38-4ed2-833f-bb51a3ee1581",
//                userBean.id,
//                userBean.nickname,
//                userBean.avatar,
//                "https://api.live.yctourism.net/",
//                userBean.jwt_token,
//                "ant",
//                "ant", LibCore.getInfo().appId.toString(),
//                UuidUtil.getUniqueID(LibCore.getContext()),
//                Build.MODEL, BuildConfig.VERSION_CODE.toString()
//            )
//        }
//        init(
//            LibCore.getContext(),
//            config,
//            LivePrototype.Role.AUDIENCE,
//            { url: String? ->
//                Router.turnTo(App.mLifecycleCallListener.mTopActivity, YcWebViewActivity::class.java)
//                    .putExtra(Const.Extra.Web_View_Url, url)
//                    .putExtra(Const.Extra.Web_View_Title_Visible, false)
//                    .putExtra(Constants.Extra.Yc_Web_View_Can_Share, true)
//                    .start()
//            },
//            { title: String?, content: String?, image: String?, link: String? ->
//                BusinessHelper.shareWx(
//                    App.mLifecycleCallListener.mTopActivity, title, content, image, UrlUtil.appendParameterCompat(link, "other", "ant_ant")
//                ) {}
//
//            }, { _: File, _: Function1<String, Unit> -> },
//            { },
//            { _: Activity?, _: String?, _: Float?, _: Float? -> }
//        ) { _: Activity?, _: Bitmap? -> }
    }
}